package com.example.aijiancece.api;

import android.util.Base64;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class SparkApiManager {
    private static final String HOST_URL = "wss://spark-api.xf-yun.com/v3.5/chat";
    private static final String APP_ID = "a7db5843";
    private static final String API_SECRET = "NTY2Yzg0MmE0ZTAxZmM3OWRiMjEzOGY4";
    private static final String API_KEY = "51fcf2bbb9fe3912557b5b6c01a5cd0b";

    private WebSocket webSocket;
    private StringBuilder responseBuilder = new StringBuilder();
    private OnResponseListener listener;

    public interface OnResponseListener {
        void onSuccess(String response);
        void onError(String error);
    }

    public void setOnResponseListener(OnResponseListener listener) {
        this.listener = listener;
    }

    public void detectContent(String content) {
        try {
            String url = getAuthUrl();
            OkHttpClient client = new OkHttpClient.Builder().build();
            Request request = new Request.Builder().url(url).build();

            webSocket = client.newWebSocket(request, new WebSocketListener() {
                @Override
                public void onMessage(WebSocket webSocket, String text) {
                    handleMessage(text);
                }

                @Override
                public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                    if (listener != null) {
                        listener.onError(t.getMessage());
                    }
                }
            });

            // 发送检测请求
            JSONObject message = new JSONObject();
            message.put("header", new JSONObject()
                    .put("app_id", APP_ID));

            message.put("parameter", new JSONObject()
                    .put("chat", new JSONObject()
                            .put("domain", "generalv3.5")
                            .put("temperature", 0.5)
                            .put("max_tokens", 4096)));

            JSONArray textArray = new JSONArray();
            textArray.put(new JSONObject()
                    .put("role", "user")
                    .put("content", "请分析以下内容是否由AI生成，给出分析结果和理由：" + content));

            message.put("payload", new JSONObject()
                    .put("message", new JSONObject()
                            .put("text", textArray)));

            webSocket.send(message.toString());

        } catch (Exception e) {
            if (listener != null) {
                listener.onError(e.getMessage());
            }
        }
    }

    private void handleMessage(String message) {
        try {
            JSONObject jsonObject = new JSONObject(message);
            JSONObject header = jsonObject.getJSONObject("header");
            int status = header.getInt("status");

            if (header.getInt("code") != 0) {
                if (listener != null) {
                    listener.onError(header.getString("message"));
                }
                return;
            }

            JSONObject payload = jsonObject.getJSONObject("payload");
            JSONObject choices = payload.getJSONObject("choices");
            JSONArray texts = choices.getJSONArray("text");
            JSONObject text = texts.getJSONObject(0);
            String content = text.getString("content");

            responseBuilder.append(content);

            if (status == 2) { // 最后一条消息
                if (listener != null) {
                    listener.onSuccess(responseBuilder.toString());
                }
                responseBuilder = new StringBuilder();
                webSocket.close(1000, null);
            }

        } catch (Exception e) {
            if (listener != null) {
                listener.onError(e.getMessage());
            }
        }
    }

    private String getAuthUrl() throws Exception {
        String date = getGMTDate();
        String signature_origin = "host: " + new URI(HOST_URL).getHost() + "\n";
        signature_origin += "date: " + date + "\n";
        signature_origin += "GET " + new URI(HOST_URL).getPath() + " HTTP/1.1";

        Mac mac = Mac.getInstance("hmacsha256");
        mac.init(new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), "hmacsha256"));
        byte[] signature = mac.doFinal(signature_origin.getBytes(StandardCharsets.UTF_8));
        String signature_sha = Base64.encodeToString(signature, Base64.NO_WRAP);

        String authorization_origin = String.format(
                "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                API_KEY, "hmac-sha256", "host date request-line", signature_sha
        );

        String authorization = Base64.encodeToString(
                authorization_origin.getBytes(StandardCharsets.UTF_8), 
                Base64.NO_WRAP
        );

        return HOST_URL + "?" 
                + "authorization=" + authorization 
                + "&date=" + date 
                + "&host=" + new URI(HOST_URL).getHost();
    }

    private String getGMTDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new Date());
    }
} 